package com.meida.module.bus.provider.api.soap;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Maps;
import com.meida.module.bus.client.entity.BusReceiptDeliveryRecord;
import com.meida.module.bus.client.entity.BusReceiptDeliveryRecordBack;
import com.meida.module.bus.client.entity.BusReceiptDeliveryReq;
import com.meida.module.bus.provider.api.util.ApiConstants;
import org.w3c.dom.Document;

import javax.xml.xpath.XPathConstants;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class SyncSapUtil {
    public static void main(String[] args) throws Exception {
//        syncSap(null);
    }

    /**
     * kind 0 发料 1 冲销
     *
     * @param records
     * @param kind
     * @throws Exception
     */
    public static Map<String, String> syncSap(List<BusReceiptDeliveryReq> records, int kind) throws Exception {
        StringBuffer content = new StringBuffer();
        content.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">");
        content.append("   <soapenv:Header/>");
        content.append("   <soapenv:Body>");                                            // 外围系统 固定值：PMS
        content.append("      <urn:Zybc01Ifs015>");                                     // 业务类型 固定值：ZYBC01_IFS015
        content.append("         <!--Optional:-->");
        content.append("         <IsInput>");
        content.append("            <Dest>");
        content.append("               <DestId>PMS01</DestId>");
        content.append("               <BussTp>ZYBC01_IFS016</BussTp>");
        content.append("            </Dest>");
        content.append("            <Data>");
        content.append("            <Items>");
        content.append("               <!--Zero or more repetitions:-->");
        records.stream().forEach(recordObj -> {
            content.append("            <item>");
            content.append("               <Zid>" + recordObj.getRecDecId() + "</Zid>");           // 发料ID号
            content.append("               <Zitem>" + recordObj.getRecDecId() + "</Zitem>");       // 发料行项目
            content.append("               <Action>" + recordObj.getAction() + "</Action>");       // 操作可以在 MIGO 事务中执行
            content.append("               <Mblnr>" + "" + "</Mblnr>");                            // 物料凭证编号
            content.append("               <Mblpo>" + "" + "</Mblpo>");                            // 物料凭证中的项目
            content.append("               <Mjahr>" + "" + "</Mjahr>");                            // 物料凭证的年份
            content.append("               <Bldat>" + DateUtil.format(recordObj.getBldat(), DatePattern.NORM_DATE_PATTERN) + "</Bldat>");          // 凭证中的凭证日期
            content.append("               <Budat>" + DateUtil.format(recordObj.getBudat(), DatePattern.NORM_DATE_PATTERN) + "</Budat>");          // 凭证中的过帐日期
            content.append("               <Bktxt>" + recordObj.getBktxt() + "</Bktxt>");          // 凭证抬头文本
            content.append("               <Rsnum>" + Long.valueOf(recordObj.getReserveNo()) + "</Rsnum>");      // 预留/相关需求的编号
            content.append("               <Rspos>" + recordObj.getReserveRow() + "</Rspos>");     // 预留 / 相关需求的项目编号
            content.append("               <Erfmg>" + recordObj.getDeliveryNumThis() + "</Erfmg>");     // 以录入项单位表示的数量
            content.append("               <Wempf>" + recordObj.getSupplierCodeForRecord() + "</Wempf>");   // 收货方
            content.append("               <Charg>" + "" + "</Charg>");                            // 批号
            content.append("               <Lgort>" + recordObj.getLgort() + "</Lgort>");          // 库存地点

            content.append("               <Posid>" + recordObj.getMaterialWbsCode() + "</Posid>");// WBS元素
            content.append("               <Sobkz>" + "Q" + "</Sobkz>");                           // 特殊库存标识
            content.append("               <Movereas>" + "" + "</Movereas>");                      // 移动原因

            content.append("               <Ext01>" + "" + "</Ext01>");                            // 扩展字段
            content.append("               <Ext02>" + "" + "</Ext02>");                            // 扩展字段
            content.append("               <Ext03>" + "" + "</Ext03>");                            // 扩展字段
            content.append("               <Ext04>" + "" + "</Ext04>");                            // 扩展字段
            content.append("               <Ext05>" + "" + "</Ext05>");                            // 扩展字段
            content.append("            </item>");
        });
        content.append("            </Items>");
        content.append("            </Data>");
        content.append("         </IsInput>");
        content.append("      </urn:Zybc01Ifs015>");
        content.append("   </soapenv:Body>");
        content.append("</soapenv:Envelope>");
//        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">\n" +
//            "   <soapenv:Header/>\n" +
//            "   <soapenv:Body>\n" +
//            "      <urn:Zybc01Ifs015>\n" +
//            "         <!--Optional:-->\n" +
//            "         <IsInput>\n" +
//            "            <Dest>\n" +
//            "               <DestId>PMS</DestId>\n" +
//            "               <BussTp>ZYBC01_IFS015</BussTp>\n" +
//            "            </Dest>\n" +
//            "         </IsInput>\n" +
//            "      </urn:Zybc01Ifs015>\n" +
//            "   </soapenv:Body>\n" +
//            "</soapenv:Envelope>";
        String url = "http://58.215.120.194:8200/sap/bc/srt/rfc/sap/zybc01_ifs015/500/zybc01_ifs015/zybc01_ifs015";
        return GetDate(content.toString(), url);
    }

    private static Map<String, String> GetDate(String xml, String url) throws Exception {

        Map<String, String> rs = Maps.newHashMap();
        StringBuffer stringBuffer = testWebService(xml, url);
        Document docResult = XmlUtil.parseXml(stringBuffer.toString());
        String status = docResult.getElementsByTagName("Status").item(0).getFirstChild().getNodeValue();
        String msg = docResult.getElementsByTagName("MessText").item(0).getFirstChild().getNodeValue();
        StaticLog.info("sap recDelivery value:" + status);
        StaticLog.info("sap recDelivery MessText:" + msg);
        System.out.println("xml::" + xml);
        //处理返回数据
        String xmlResult = stringBuffer.toString().replace("<", "<");
        System.out.println("xmlResult:" + xmlResult);
        rs.put(ApiConstants.MAP_MSGTYFROMSAP, status);
        rs.put(ApiConstants.MAP_MSGTXFROMSAP, msg);
        return rs;
    }

    // 调用WS
    private static StringBuffer testWebService(String sendMsg, String INVOICE_WS_URL) throws Exception {
        //拼接请求报文
        System.out.println("sendMsg:" + sendMsg);
        // 开启HTTP连接ַ
        InputStreamReader isr = null;
        BufferedReader inReader = null;
        StringBuffer result = null;
        OutputStream outObject = null;
        try {
            URL url = new URL(INVOICE_WS_URL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            // 设置HTTP请求相关信息
            httpConn.setRequestProperty("Content-Length",
                String.valueOf(sendMsg.getBytes().length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            // 进行HTTP请求
            outObject = httpConn.getOutputStream();
            outObject.write(sendMsg.getBytes());

            if (200 != (httpConn.getResponseCode())) {
                throw new Exception("HTTP Request is not success, Response code is " + httpConn.getResponseCode());
            }
            // 获取HTTP响应数据
            isr = new InputStreamReader(
                httpConn.getInputStream(), "utf-8");
            inReader = new BufferedReader(isr);
            result = new StringBuffer();
            String inputLine;
            while ((inputLine = inReader.readLine()) != null) {
                result.append(inputLine);
            }
            return result;

        } catch (IOException e) {
            throw e;
        } finally {
            // 关闭输入流
            if (inReader != null) {
                inReader.close();
            }
            if (isr != null) {
                isr.close();
            }
            // 关闭输出流
            if (outObject != null) {
                outObject.close();
            }
        }

    }

    /**
     *
     * @param records
     * @throws Exception
     */
    public static Map<String, String> syncSapForCharOff(List<BusReceiptDeliveryRecordBack> records) throws Exception {
        StringBuffer content = new StringBuffer();
        content.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">");
        content.append("   <soapenv:Header/>");
        content.append("   <soapenv:Body>");                                            // 外围系统 固定值：PMS
        content.append("      <urn:Zybc01Ifs015>");                                     // 业务类型 固定值：ZYBC01_IFS015
        content.append("         <!--Optional:-->");
        content.append("         <IsInput>");
        content.append("            <Dest>");
        content.append("               <DestId>PMS01</DestId>");
        content.append("               <BussTp>ZYBC01_IFS016</BussTp>");
        content.append("            </Dest>");
        content.append("            <Data>");
        content.append("            <Items>");
        content.append("               <!--Zero or more repetitions:-->");
        records.stream().forEach(recordObj -> {
            content.append("            <item>");
            content.append("               <Zid>" + "" + "</Zid>");                                // 发料ID号
            content.append("               <Zitem>" + "" + "</Zitem>");                            // 发料行项目
            content.append("               <Action>" + "A02" + "</Action>");                       // 操作可以在 MIGO 事务中执行
            content.append("               <Mblnr>" + recordObj.getMblnrFromSap() + "</Mblnr>");   // 物料凭证编号
            content.append("               <Mblpo>" + recordObj.getMblpoFromSap() + "</Mblpo>");   // 物料凭证中的项目
            content.append("               <Mjahr>" + recordObj.getMjahrFromSap() + "</Mjahr>");   // 物料凭证的年份
            content.append("               <Bldat>" + DateUtil.format(recordObj.getBldatBk(), DatePattern.NORM_DATE_PATTERN) + "</Bldat>");          // 凭证中的凭证日期
            content.append("               <Budat>" + DateUtil.format(recordObj.getBudatBk(), DatePattern.NORM_DATE_PATTERN) + "</Budat>");          // 凭证中的过帐日期
            content.append("               <Bktxt>" + recordObj.getBktxtBk() + "</Bktxt>");        // 凭证抬头文本
            content.append("               <Rsnum>" + "" + "</Rsnum>");                            // 预留/相关需求的编号
            content.append("               <Rspos>" + "" + "</Rspos>");                            // 预留 / 相关需求的项目编号
            content.append("               <Erfmg>" + recordObj.getCharOffCount() + "</Erfmg>");   // 以录入项单位表示的数量
            content.append("               <Wempf>" + "" + "</Wempf>");                            // 收货方
            content.append("               <Charg>" + "" + "</Charg>");                            // 批号
            content.append("               <Lgort>" + "" + "</Lgort>");                            // 库存地点
            content.append("               <Posid>" + "" + "</Posid>");                            // WBS元素
            content.append("               <Sobkz>" + "" + "</Sobkz>");                            // 特殊库存标识
            content.append("               <MoveReas>" + "0001" + "</MoveReas>");                  // 移动原因
            content.append("               <Ext01>" + "" + "</Ext01>");                            // 扩展字段
            content.append("               <Ext02>" + "" + "</Ext02>");                            // 扩展字段
            content.append("               <Ext03>" + "" + "</Ext03>");                            // 扩展字段
            content.append("               <Ext04>" + "" + "</Ext04>");                            // 扩展字段
            content.append("               <Ext05>" + "" + "</Ext05>");                            // 扩展字段
            content.append("            </item>");
        });
        content.append("            </Items>");
        content.append("            </Data>");
        content.append("         </IsInput>");
        content.append("      </urn:Zybc01Ifs015>");
        content.append("   </soapenv:Body>");
        content.append("</soapenv:Envelope>");
//        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">\n" +
//            "   <soapenv:Header/>\n" +
//            "   <soapenv:Body>\n" +
//            "      <urn:Zybc01Ifs015>\n" +
//            "         <!--Optional:-->\n" +
//            "         <IsInput>\n" +
//            "            <Dest>\n" +
//            "               <DestId>PMS</DestId>\n" +
//            "               <BussTp>ZYBC01_IFS015</BussTp>\n" +
//            "            </Dest>\n" +
//            "         </IsInput>\n" +
//            "      </urn:Zybc01Ifs015>\n" +
//            "   </soapenv:Body>\n" +
//            "</soapenv:Envelope>";
        String url = "http://58.215.120.194:8200/sap/bc/srt/rfc/sap/zybc01_ifs015/500/zybc01_ifs015/zybc01_ifs015";
        return GetDate(content.toString(), url);
    }
}
